package base.service.impl;

import base.mapper.UserInfoMapper;
import base.pojo.UserInfo;
import base.service.IUserInfoService;
import common.Const;
import common.ServerResponse;
import common.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.BitOperationUtil;

/**
 * 用户相关服务
 * @author LiuZhi
 */
@Service
public class UserInfoServiceImpl implements IUserInfoService
{
    @Autowired
    UserInfoMapper userInfoMapper;

    public ServerResponse update(UserInfo userInfo) throws Exception
    {
        int ret  =   userInfoMapper.updateByPrimaryKey(userInfo);

        if( ret  <=  0)
        {
            throw new RuntimeException("乐观锁失败,UserInfo:"+userInfo.getId()+"--Version:"+userInfo.getVersion());
        }
        return ServerResponse.createBySuccess();
    }

    public ServerResponse add(UserInfo userInfo) throws Exception
    {
        int ret =   userInfoMapper.insert(userInfo)                      ;
        if( ret <=  0 ){
            throw new RuntimeException("创建用户详情信息错误")            ;
        }
        return ServerResponse.createBySuccess()                          ;
    }

    @Override
    public UserInfo get(Long id)
    {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    public void bindPhone(Long id, Long state,String phoneNumber)
    {
        userInfoMapper.updateState(id, state,phoneNumber);
    }

    @Override
    public int checkPhone(String phone)
    {
        return userInfoMapper.checkPhone(phone) ;
    }

    public void bindEmail(Long id, Long state, String email) {
        userInfoMapper.bindEmail(id,state,email);
    }

    public int checkEmil(String email)
    {
        return userInfoMapper.checkEmail(email);
    }

    public UserInfo getCurrent()
    {
        return get(UserContext.getCurrentUser().getId());
    }

    public ServerResponse updateBasicInfo(UserInfo userInfo) {
        UserInfo old = this.getCurrent()                                ;
        //设置新的属性值
        old.setEducationBackground(userInfo.getEducationBackground())   ;
        old.setHouseCondition(userInfo.getHouseCondition())             ;
        old.setIncomeGrade(userInfo.getIncomeGrade())                   ;
        old.setKidCount(userInfo.getKidCount())                         ;
        old.setMarriage(userInfo.getMarriage())                         ;
        //判断是否具有状态码
        if(!old.getHasBaseInfo())
        {
            old.setBitState(BitOperationUtil.addState(old.getBitState(),Const.OP_BASE_INFO));
        }
        if(userInfoMapper.updateByPrimaryKey(old)  >   0)
        {
            return ServerResponse.createBySuccess() ;
        }
        return ServerResponse.createByError()       ;
    }
}
